package com.tatesuke.automine.board.random;

import java.util.ArrayList;
import java.util.List;

import com.tatesuke.automine.board.CellState;

class Cell {

	private final List<Cell> neighbors;

	boolean isBomb = false;
	private boolean isFlag = false;
	private boolean isOpen = false;

	Cell () {
		neighbors = new ArrayList<Cell>(8);
	}

	void setBomb(boolean isBomb) {
		this.isBomb = isBomb;
	}

	void addNeigbor(Cell neighbor) {
		if (neighbor != null) {
			neighbors.add(neighbor);
		}
	}

	CellState getType() {
		CellState cellType;

		if (isFlag) {
			cellType = CellState.FLAG;
		} else if (isOpen) {
			cellType = CellState.OPEN;
		} else {
			cellType = CellState.CLOSE;
		}

		return cellType;
	}

	boolean isBurn() {
		return isOpen && isBomb;
	}

	void open() {
		if (!isOpen && !isFlag) {
			isOpen = true;

			if (getHint() == 0) {
				openAllNeighbors();
			}
		}
	}

	void toggleFlag() {
		if (isFlag) {
			isFlag = false;
		} else if (!isOpen) {
			isFlag = true;
		}
	}

	int getHint() {
		int count = 0;

		for (Cell neighbor : neighbors) {
			if (neighbor.isBomb) {
				count++;
			}
		}

		return count;
	}

	void openAllNeighbors() {
		for (Cell neighbor : neighbors) {
			neighbor.open();
		}
	}

	public int countNeighbor(CellState flag) {
		int count = 0;

		for (Cell neighbor : neighbors) {
			if (neighbor.getType() == CellState.FLAG) {
				count++;
			}
		}

		return count;
	}


}
